<?php
namespace app\cgi\controller;

use think\Db;

class Community extends Base{
    protected function _initialize() {
        $this->authentication();
    }

    public function login(){
        $account = $this->request->post('account');
        $password= $this->request->post('password');
        !$account && $this->responseError('请输入帐号');
        !$password && $this->responseError('请输入密码');

        $auth_info = Db::name('community_user')->where(['account'=>$account,'isdelete'=>0,'status'=>1,'ty_id'=>$this->ty_id])->field('id,realname,password,status')->find();
        is_null($account) && $this->responseError('帐号不存在或已禁用');
        if ( $auth_info['password'] != password_hash_tp($password)) {
            $this->responseError('密码错误');
        }
        $role = Db::name('community_role_user')->alias('a')->join('__COMMUNITY_ROLE__ b','b.id=a.role_id')->where(['isdelete'=>0,'status'=>1,'user_id'=>$auth_info['id']])->field('name')->select();
        $role = is_null($role)?[]:array_column($role,'name');
        Db::name('community_user')->where(['id'=>$auth_info['id']])->inc('login_count',1)->update(['openid'=>$this->userInfo['openid'],'last_login_time'=>time(),'last_login_ip'=>$this->request->ip()]);
        if( $this->request->post('form_id') && 'the formId is a mock one' !== $this->request->post('form_id') ) {
            Db::name('form_id')->insert(['ty_id'=>$this->ty_id,'user_id'=>$auth_info['id'],'from_id'=>$this->request->post('form_id'),'create_time'=>time()]);
        }
        $this->response('',[
            'user'=>[
                'id'=>$auth_info['id'],'account'=>$account,'realname'=>$auth_info['realname'],'role'=>$role
                ],
            'nodes'=>$this->getUserMenu($auth_info['id'])
        ]);
    }

}
